package net.gzw1993.runmate.activity;

import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.maps2d.model.Polyline;
import com.amap.api.maps2d.model.PolylineOptions;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import net.gzw1993.runmate.R;

import java.util.ArrayList;
import java.util.List;

public class RuningActivity extends AppCompatActivity implements AMapLocationListener, LocationSource {

    @ViewInject(R.id.run_mapView)
    private MapView mapView;
    @ViewInject(R.id.sport_distance_km)
    private TextView tvDistance;

    private AMap aMap;
    private LocationManagerProxy mAMapLocationManager;
    private LocationSource.OnLocationChangedListener mListener;
    /**
     * 在地图上绘制折线的对象
     */
    private Polyline polyline;

    /**
     * 地图上所有点的集合
     */
    private List<LatLng> pointList = new ArrayList<>();

    /**
     * 运动是否暂停的flag
     */
    private boolean isPause = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_runing);
        ViewUtils.inject(this);
        mapView.onCreate(savedInstanceState);
        initView();
        drawLine();
    }

    private void drawLine() {
        polyline = aMap.addPolyline((new PolylineOptions())
                .addAll(pointList)
                .width(10).setDottedLine(true).geodesic(true)
                .color(Color.argb(255, 1, 1, 1)));
    }


    public void initView() {

        aMap = mapView.getMap();
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);
        setUpMap();
    }


    private void setUpMap() {
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.mipmap.location_marker));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationRotateAngle(180);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);
        aMap.moveCamera(CameraUpdateFactory.zoomBy(5));

    }


    @OnClick(R.id.sport_pause)
    public void onSportPause(View v) {
        TextView tvPause = (TextView) v;
        if (!isPause) {
            isPause = true;
            tvPause.setText("开始");
        } else {
            isPause = false;
            tvPause.setText("暂停");
        }
    }

    /**
     * 此方法需存在
     */
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 此方法需存在
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 此方法需存在
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 此方法已经废弃
     */
    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation.getAMapException().getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                if (!isPause) {  //没有暂停的时候进行下面的测距处理
                    // 将定位的点添加到集合
                    pointList.add(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude()));
                    // 给折线设置坐标点
                    polyline.setPoints(pointList);
                    // 运动的的总距离
                    int countDistance = 0;
                    // 计算运动的总距离
                    for (int i = 0; i < pointList.size() - 1; i++) {
                        countDistance += AMapUtils.calculateLineDistance(pointList.get(i), pointList.get(i + 1));
                    }

                    //在控件上显示距离
                    tvDistance.setText(countDistance / 1000);
                }

            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(LocationSource.OnLocationChangedListener listener) {
        mListener = listener;
        if (mAMapLocationManager == null) {
            mAMapLocationManager = LocationManagerProxy.getInstance(this);
            //此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            //注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
            //在定位结束后，在合适的生命周期调用destroy()方法
            //其中如果间隔时间为-1，则定位只定一次
            mAMapLocationManager.requestLocationData(
                    LocationProviderProxy.AMapNetwork, 10 * 1000, 10, this);
        }
    }


    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mAMapLocationManager != null) {
            mAMapLocationManager.removeUpdates(this);
            mAMapLocationManager.destroy();
        }
        mAMapLocationManager = null;
    }

    @OnClick(R.id.sport_start)
    public void onClick(View v) {

    }
}
